﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using WIKID.Model;
using WIKID.Common;
using WIKID.Accessor;

namespace WIKID.Controller
{
    class AccountController
    {
        public Boolean isAccountsFolderEmpty() 
        {
            Utils utils = new Utils();
            return utils.IsFolderEmpty(null);
        }
        
        //load all acounts
        public List<AccountModel> getAllAcounts()
        {
            Utils utils = new Utils();
            XMLReader xmlReader = new XMLReader();
            List<string> lsFiles = utils.ListingXMLFiles(Constants.ACCOUNTS_FOLDER);
            List<AccountModel> accountModels = new List<AccountModel>();
            for (int i = 0; i < lsFiles.Count; i++)
            {
                accountModels.Add(xmlReader.getAccountByXmlFileName(lsFiles[i]));
            }
            return accountModels;
        }
        
        // check if an account name existed
        private bool checkAccount(String s)
        {
            Utils utils = new Utils();
            List<string> lsFiles = utils.ListingXMLFiles(Constants.ACCOUNTS_FOLDER);
            List<string> accountNames = new List<string>();
            for (int i = 0; i < lsFiles.Count; i++) 
            { 
                accountNames.Add(lsFiles[i].Substring(lsFiles[i].IndexOf("_")+1));
            }
            if (accountNames.Contains(s)) return false;
            else return true;
        }

        // check Login by AccountName and AccountPassword
        public bool CheckLoginByAccAndPass(AccountModel account, String passId)
        {
            if (account.PassId.Equals(passId))
            {
                return true;
            }
            else 
            {
                return false;
            }

        }

        // get all Account Id for all accounts
        private List<int> getListOfAccId()
        {
            Utils utils = new Utils();
            List<string> lsFiles = utils.ListingXMLFiles(Constants.ACCOUNTS_FOLDER);
            if (lsFiles.Count == 0) return new List<int>();
            else
            {
                List<int> ids = new List<int>();
                foreach (String fileName in lsFiles)
                {
                    ids.Add(int.Parse(fileName.Substring(0, fileName.IndexOf("_"))));
                }
                return ids;
            }
        }

        // create name for new account's xml file
        private String createNameForNewXmlFile(String accName)
        {
            List<int> ids = getListOfAccId();
            if (ids.Count == 0) return "1_" + accName;
            else
            {
                ids.Sort();
                return (ids[ids.Count - 1] + 1).ToString() + "_" + accName;
            }
        }

        // create contents for new account xml
        public bool CreateNewAccount(AccountModel accountModel)
        {
            if (checkAccount(accountModel.AccName))
            {
                XmlDocument doc = new XmlDocument();
                XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                XmlNode xmlRoot = doc.CreateElement("account");
                doc.InsertBefore(xmlDeclaration, doc.DocumentElement);
                doc.AppendChild(xmlRoot);
                 

                String fileName = createNameForNewXmlFile(accountModel.AccName);
                String id = fileName.Substring(0, fileName.IndexOf("_"));

                XmlAttribute attribute = doc.CreateAttribute("accId");
                attribute.Value = id;
                xmlRoot.Attributes.Append(attribute);

                XmlElement accountNameNode = doc.CreateElement("accName");
                accountNameNode.InnerText = accountModel.AccName;
                xmlRoot.AppendChild(accountNameNode);

                XmlElement accountPicNode = doc.CreateElement("accPic");
                accountPicNode.InnerText = accountModel.AccPic;
                xmlRoot.AppendChild(accountPicNode);

                XmlElement accountAgeNode = doc.CreateElement("accAge");
                accountAgeNode.InnerText = accountModel.AccAge.ToString();
                xmlRoot.AppendChild(accountAgeNode);

                XmlElement passIdNode = doc.CreateElement("passId");
                passIdNode.InnerText = accountModel.PassId;
                xmlRoot.AppendChild(passIdNode);

                XmlElement passPicNode = doc.CreateElement("passPic");
                passPicNode.InnerText = accountModel.PassPic;
                xmlRoot.AppendChild(passPicNode);

                string filename = @"Accounts\" + fileName + ".xml";

                doc.Save(filename);

                return true;
            }
            return false;
        }

        // get AccountModel from accName and accId
        public AccountModel getAccountModel(string accName, string accId) 
        {
            XMLReader xmlReader = new XMLReader();
            string fileName = accId + "_" + accName;
            return xmlReader.getAccountByXmlFileName(fileName);
        }

        public bool UpdateScore(AccountModel accountModel, ScoreModel scoreModel)
        {
            try
            {
                XMLWriter xmlWriter = new XMLWriter();
                //Remove old schedule of a lecture if exist
                foreach (ScoreModel tempScore in accountModel.Scores)
                {
                    if (tempScore.LectureId.Equals(scoreModel.LectureId))
                    {
                        accountModel.Scores.Remove(tempScore);
                        break;
                    }
                }
                accountModel.Scores.Add(scoreModel);
                xmlWriter.updateXML(accountModel);

                return true;
            }
            catch
            {
                return false;
            }
        }

    }
}
